// src/stores/chat.js
import { defineStore } from 'pinia';
import { getDialogsByUserId, createDialog, deleteDialog } from '@/api/dialog';
import { getMessagesByDialogId } from '@/api/message';

export const useChatStore = defineStore('chat', {
  state: () => ({
    dialogs: [],
    currentDialogId: null,
    messages: [],
  }),
  actions: {
    async fetchDialogs(userId) {
      const response = await getDialogsByUserId(userId);
      this.dialogs = response.data || [];
    },
    async createNewDialog(dialog) {
      await createDialog(dialog);
      await this.fetchDialogs(dialog.userId);
    },
    async deleteDialog(dialogId) {
      await deleteDialog(dialogId);
      if (this.currentDialogId === dialogId) {
        this.currentDialogId = null;
      }
      await this.fetchDialogs(1); // 假设 userId = 1，需动态获取
    },
    async loadMessages(dialogId) {
      if (dialogId) {
        const response = await getMessagesByDialogId(dialogId);
        this.messages = response.data || [];
        this.currentDialogId = dialogId;
      } else {
        this.messages = [];
        this.currentDialogId = null;
      }
    },
    setCurrentDialogId(dialogId) {
      this.currentDialogId = dialogId;
    },
    addMessage(message) {
      this.messages.push(message);
    },
  },
});